﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;

namespace lfm
{
    public enum Order
    {
        dateadded,
        popularity
    }

    internal class Base
    {
        public String Apikey { get; set; }
        public String SecretKey { get; set;}

        internal static string iKey = "66777b2e68e4143566b7ecc71ea18e8a";

        internal static string BaseUrl = "http://ws.audioscrobbler.com/2.0/?";

        public void SetUp(String key)
        {
            Apikey = key;
        }

        /// <summary>
        /// Returns String for XML based requests
        /// </summary>
        public static String APIUrl = BaseUrl + "api_key=" + iKey;

        /// <summary>
        /// Returns String for JSON based requests
        /// </summary>
        internal static String APIUrlJson = BaseUrl + "api_key=" + iKey + "&format=json";


        internal static async Task<String> DownloadString(Uri _uri)
        {
            // Create a GZIP capable header
            System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler();
            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
            //Create our actaul request client
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler);
            System.Net.Http.HttpResponseMessage response = await client.GetAsync(_uri);
            // Ensure it's a valid response from last.fm
            await SuccessfulResponse(await response.Content.ReadAsStringAsync());
            // Cleanup any invalid XML characters, and then return the result
            return XmlCharacterWhitelist(await response.Content.ReadAsStringAsync());
        }

        /// <summary>
        /// Removes invalid XML characters from string ( so we don't break the parser)
        /// Obtained January 23 2012: 
        /// http://stackoverflow.com/questions/20762/how-do-you-remove-invalid-hexadecimal-characters-from-an-xml-based-data-source-p
        /// </summary>
        internal static string XmlCharacterWhitelist(string in_string)
        {
            if (in_string == null) return null;

            StringBuilder sbOutput = new StringBuilder();
            char ch;

            for (int i = 0; i < in_string.Length; i++)
            {
                ch = in_string[i];
                if ((ch >= 0x0020 && ch <= 0xD7FF) ||
                        (ch >= 0xE000 && ch <= 0xFFFD) ||
                        ch == 0x0009 ||
                        ch == 0x000A ||
                        ch == 0x000D)
                {
                    sbOutput.Append(ch);
                }
            }
            return sbOutput.ToString();
        }


        /// <summary>
        /// Here we handle any parsing errors
        /// </summary>
        /// <param name="e">Last.FM API response</param>
        /// <returns>Whether the server has responded with OK or not.</returns>
        internal async static Task<Boolean> SuccessfulResponse(String e)
        {
            if (e.Contains("<lfm status=\"ok\">") || e.Contains("{\"results\":{\"opensearch:Query\":"))
            {
                return true;
            }
            else
            {
                Windows.UI.Popups.MessageDialog p = new Windows.UI.Popups.MessageDialog(e, "Last.FM API Error");
                await p.ShowAsync();
                
                return false;
            }
        }
    }
}
